package com.lagou.seckill.common.dto;


import com.lagou.seckill.common.enums.ErrorCodeEnum;
import org.springframework.util.StringUtils;
import com.lagou.seckill.common.utils.JSONUtils;

import java.text.MessageFormat;

/**
 * 返回数据封装对象
 */
public class Result<M> {


    private Object code;

    private String msg;

    private M data;

    private boolean success;

    public Result() {
    }

    public Result(M data, String code, String msg) {
        this.success = true;
        if (!StringUtils.hasText(code)) {
            code = ErrorCodeEnum.SYSTEM_ERROR_B0001.getCode();
            this.success = false;
        }
        this.data = data;
        this.code = code;
        this.msg = msg;
    }

    public Result(M data, String code, String msg, boolean success) {
        if (!StringUtils.hasText(code)) {
            code = ErrorCodeEnum.SYSTEM_ERROR_B0001.getCode();
        }
        this.data = data;
        this.code = code;
        this.msg = msg;
        this.success = success;
    }

    public Result(M data, Integer code, String msg, boolean success) {
        this.data = data;
        this.code = code;
        this.msg = msg;
        this.success = success;
    }


    public Result(Exception ex) {
        this.code = ErrorCodeEnum.SYSTEM_ERROR_B0001.getCode();
        this.msg = ex.getMessage();
    }

    public Result(M data, ErrorCodeEnum msgDefined) {
        if (data != null) {
            this.data = data;
        }
        this.code = msgDefined.getCode();
        this.msg = msgDefined.getDescription();
        this.success = ErrorCodeEnum.SUCCESS.equals(msgDefined);
    }

    public Result(M data, String msg) {
        if (data != null) {
            this.data = data;
        }
        this.code = ErrorCodeEnum.SUCCESS.getCode();
        this.msg = msg;
        this.success = true;
    }

    public Result(ErrorCodeEnum msgDefined) {
        this(msgDefined, null);
    }

    public Result(ErrorCodeEnum msgDefined, String info) {
        this.code = msgDefined.getCode();
        this.msg = MessageFormat.format(msgDefined.getDescription(), info);
        this.success = ErrorCodeEnum.SUCCESS.equals(msgDefined);
    }

    public Object getCode() {
        return code;
    }

    public void setCode(Object code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public M getData() {
        return data;
    }

    public void setData(M data) {
        this.data = data;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    @Override
    public String toString() {
        return JSONUtils.write(this);
    }
}
